import 'dart:collection';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/putaway/putawaydialogscreen.dart';
import 'package:opene/ui/putaway/putawaylocationscreen.dart';
import 'package:opene/ui/putaway/putawaymodel.dart';
import 'package:toast/toast.dart';



class PutawayScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return PutawayScreenPage();
  }
}

class PutawayScreenPage extends StatefulWidget {
  @override
  _PutawayPageState createState() => _PutawayPageState();
}

class _PutawayPageState extends BaseState<PutawayScreen> {
  List<PutawayContainer> data = new List();

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "Putaway";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setLayoutBottomContentGone();
    Future.delayed(Duration(milliseconds: 300), () {
      setState(() {
        getContainerNoList();
      });
    });
  }

  void didPopNext() {
    setState(() {
      // 这里刷新页面状态
    });
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 0, top: 10, right: 0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            margin: const EdgeInsets.only(left: 15, top: 0, right: 15, bottom: 0),
            width: double.infinity,
            child: ConstrainedBox(
              constraints: BoxConstraints(maxHeight: 35),
              child: TextField(
                controller: textEditingController,
                textInputAction: TextInputAction.search,
                onSubmitted: (String text) {
                  print('Searching for $text');
                  if (Utils.isEmpty(text)) {
                    return;
                  }
                  putaway(text);
                },
                // autofocus: true,
                decoration: InputDecoration(
                  suffixIcon: IconButton(
                    padding: EdgeInsets.all(2.0),
                    icon: Icon(
                      Icons.qr_code_scanner,
                      size: 28,
                      color: MyAppTheme.nearlyBlue,
                    ),
                    onPressed: () {
                      // requestPermissions();
                      // Utils.scanBarcode(context);
                      Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                        return ScanCode();
                      })).then((text) {
                        if (text == null) {
                          return;
                        }
                        setState(() {
                          textEditingController.text = text;
                        });
                        print(text); //拿到扫描结果
                        putaway(text);
                      });
                    },
                  ),
                  border: OutlineInputBorder(
                    borderSide: BorderSide(
                      color: MyAppTheme.nearlyBlue,
                    ),
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  enabledBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点之外的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  focusedBorder: OutlineInputBorder(
                    borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                    // 设置焦点时的边框颜色
                    borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                  ),
                  hintText: "scan inbound lpn barcode",
                  filled: true,
                  fillColor: MyAppTheme.white,
                  //隐藏下划线
                  //border: InputBorder.none,
                  hintStyle: TextStyle(color: Colors.grey),
                  contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                ),
                onChanged: (text) {
                  code = text;
                },
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.only(left: 15,top: 5),
            child: Text(
              "Waiting for putaway",
              style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
            ),
          ),
          Container(
            margin: const EdgeInsets.only(left: 0, top: 5, right: 0, bottom: 0),
            width: double.infinity,
          ),
          Expanded(
            child: Container(
              margin: EdgeInsets.only(left: 15, right: 10),
              child: setListView(),
            ),
          ),
        ],
      ),
    );
  }

  ListView setListView() {
    return ListView.builder(
      itemCount: data == null ? 0 : data.length,
      itemBuilder: (context, index) {
        PutawayContainer tally = data[index];
        if(tally.isShow==null){
          tally.isShow = false;
        }
        return Column(
          children: [
            Row(
              children: [
                Expanded(
                  flex: 2, //设置权重
                  child:  Text(Utils.isEmpty(tally.tallyFinishDate)?Utils.getStringisEmpty(tally.containerNo):'${Utils.getStringisEmpty(tally.containerNo)}(${Utils.getStringisEmpty(tally.tallyFinishDate)})',
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: MyAppTheme.color_333333, fontSize: 12.0),
                  ),
                ),
                GestureDetector(
                  onTap: () {
                    List<PutawayLPNSkus>  containerDetail = tally.containerDetail;
                    if(containerDetail==null||containerDetail.length==0){
                      containerLpn(tally.warehousingNotifyId, index);
                    }else{
                      setState(() {
                        tally.isShow = !tally.isShow;
                        data[index] = tally;
                      });
                    }
                  },
                  child: Icon(
                    tally.isShow ? Icons.keyboard_arrow_up : Icons.keyboard_arrow_down,
                    size: 20,
                    color: MyAppTheme.nearlyBlue,
                  ),
                ),
              ],
            ),
            Visibility(visible: tally.isShow ? true : false, child: Container(
              margin: EdgeInsets.only(left: 5,top: 5),
              child: setListViewItem(tally.containerDetail),)),
            Divider(),
          ],
        );
      },
    );
  }

  ListView setListViewItem(List<PutawayLPNSkus> list) {
    return ListView.builder(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      itemCount: list == null ? 0 : list.length,
      itemBuilder: (context, index) {
        PutawayLPNSkus lpnBean = list[index];
        return GestureDetector(
          onTap: (){
            putaway(lpnBean.lpn);
          },
          child: Text(
            Utils.getStringisEmpty(lpnBean.lpn),
            style: MyAppTheme.test12,
          ),
        );
      },
    );
  }
  void getContainerNoList() async {
    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.pendingPutawayContainers);
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      setState(() {
        PutawayContainers putawayContainer = PutawayContainers.fromJson(baseResponse.data);
        data.clear();
        if(putawayContainer.tallyFinishContainers!=null){
          data.addAll(putawayContainer.tallyFinishContainers);
        }
        if(putawayContainer.tallyContainers!=null){
          data.addAll(putawayContainer.tallyContainers);
        }
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void containerLpn(int warehousingNotifyId, int position) async {
    Map<String, dynamic> map = new HashMap();
    map["warehousingNotifyId"] = warehousingNotifyId;
    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context,Constants.containerLpn,params: map);
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      setState(() {
        PutawayContainerLPN  putawayContainerLPN = PutawayContainerLPN.fromJson(baseResponse.data);

        List<PutawayLPNSkus> lpnSkusList = new List();
        List<PutawayLpn> pendingPutawayLpns = putawayContainerLPN.pendingPutawayLpns;
        List<PutawayLpn> putawayLpns = putawayContainerLPN.putawayLpns;
        if (pendingPutawayLpns != null) {
          pendingPutawayLpns.forEach((lpNs) {
            List<PutawaySku> skus = lpNs.skus;
            for (var skus1 in skus) {
              PutawayLPNSkus lpnSkus = new PutawayLPNSkus(lpNs.lpn,lpNs.wholeCode,skus1.sku,skus1.qty,skus1.qty);
              lpnSkusList.add(lpnSkus);
            }
          });
        }
        if (putawayLpns != null) {
          putawayLpns.forEach((lpNs) {
            List<PutawaySku> skus = lpNs.skus;
            for (var skus1 in skus) {
              PutawayLPNSkus lpnSkus = new PutawayLPNSkus(lpNs.lpn,lpNs.wholeCode,skus1.sku,skus1.qty,skus1.qty);
              lpnSkusList.add(lpnSkus);
            }
          });
        }

        if (lpnSkusList.length == 0) {
          return 0;
        }
        if (data.length <= position) {
          return 0;
        }
        PutawayContainer container = data[position];
        container.containerDetail = lpnSkusList;
        if (lpnSkusList.length > 0) {
          container.isShow=true;
        }

        setState(() {
          data[position]=container;
        });
      });
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void putaway(String lpn) async {
    updateHint('');
    Map<String, dynamic> map = new HashMap();
    map["lpn"] = lpn;

    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.putaway, params: map);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      PutatayPOL3 putatayPOL3 = PutatayPOL3.fromJson(baseResponse.data);
      putatayPOL3.lpn = lpn;
      showDialog(
        context: context,
        builder: (context) => PutawaySmallTypeDialog(smallItem: putatayPOL3.smallType==1?true:false),
      ).then((value) => {
        print("result:${value}"),
        if ((value != null) && (value == "ok"))
          {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => PutawayLocationScreen(putatayPOL3: putatayPOL3)),
            ).then((value) => {getContainerNoList()})
          }
      });

    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }

  @override
  void setNext() {
    if(Utils.isEmpty(textEditingController.text)){
      ToastContext().init(context);
      Toast.show("scan inbound lpn barcode", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    putaway(textEditingController.text);
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
      hint = "";
    });
  }
}
